package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author: 李旭
 * @create: 2021-07-26 15:27
 **/
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    //统一收单下单并页面支付接口
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submit(@PathVariable Long orderId){

        return alipayService.submit(orderId);
    }
    //同步通知
    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }
    //异步通知
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){ //将异步通知中收到的所有参数都存放到map中
        System.out.println(paramsMap);
        try {
            //校验 签名是否正确
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            if (signVerified) {
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                String total_amount = paramsMap.get("total_amount");
                System.out.println("支付宝异步通知的金额是:" + total_amount);

                if("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))){
                    //交易支付成功
                    //更新支付表
                    paymentService.updatePayment(paramsMap);
                }
                return "success";
            } else {
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                //
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }



}
